package com.aos.eap.activity;

import android.content.Intent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.aos.eap.R;
import com.aos.eap.adapter.AlarmInfoListAdapter;
import com.aos.eap.adapter.RepairChooseTypeListAdapter;
import com.aos.eap.base.BaseDialogActivity;
import com.aos.eap.base.Constant;
import com.aos.eap.bean.ChooseRepairBean;
import com.aos.eap.bean.RepairBean;
import com.aos.eap.bean.RepairTypeBean;
import com.aos.eap.bean.net.BaseResponseBean;
import com.aos.eap.utils.MyUtils;
import com.aos.eap.utils.NetUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class EE_RepairActivity extends BaseDialogActivity {


    @BindView(R.id.tvUser)
    TextView tvUser;
    @BindView(R.id.etEqpId)
    FreeUI_ClearEditText etEqpId;
    @BindView(R.id.tvBdId)
    TextView tvBdId;
    @BindView(R.id.tvBdVersion)
    TextView tvBdVersion;
    @BindView(R.id.etDesc)
    FreeUI_ClearEditText etDesc;
    @BindView(R.id.tvRepairRemark)
    TextView tvRepairRemark;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.ivTypeArrow)
    ImageView ivTypeArrow;
    @BindView(R.id.flType)
    FrameLayout flType;
    @BindView(R.id.tvRepairChild)
    TextView tvRepairChild;
    @BindView(R.id.ivRepairChildArrow)
    ImageView ivRepairChildArrow;
    @BindView(R.id.flRepairChild)
    FrameLayout flRepairChild;
    @BindView(R.id.llSubType)
    LinearLayout llSubType;
    @BindView(R.id.tbBuyoff)
    ToggleButton tbBuyoff;
    @BindView(R.id.tbPeCheck)
    ToggleButton tbPeCheck;
    //    @BindView(R.id.rbPeCheck)
//    RadioButton rbPeCheck;
//    @BindView(R.id.rbNewBuild)
//    RadioButton rbNewBuild;
    @BindView(R.id.rvChooseRepairList)
    RecyclerView rvChooseRepairList;
    @BindView(R.id.etRemark)
    FreeUI_ClearEditText etRemark;
    @BindView(R.id.rvAlarmList)
    RecyclerView rvAlarmList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvDcType)
    TextView tvDcType;
    @BindView(R.id.ivDcTypeArrow)
    ImageView ivDcTypeArrow;
    @BindView(R.id.flDcType)
    FrameLayout flDcType;
    @BindView(R.id.llDcType)
    LinearLayout llDcType;
    private RepairBean repairBean;
    private FreeUI_GeneralPop typePop, childPop, dcTypePop;
    private AlarmInfoListAdapter alarmInfoListAdapter;
    private RepairChooseTypeListAdapter repairChooseTypeListAdapter;
    private boolean isFirst = true;
    private boolean isNewRcp = false;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_ee_repair;
    }

    @Override
    protected void initView() {
        tvUser.setText(Constant.CURRENT_USER);
        MyUtils.setEditTextListener(etEqpId, this, s -> {
            isFirst = true;
            requestInfoByEqpId(s);
        });
        rvAlarmList.setLayoutManager(new LinearLayoutManager(EE_RepairActivity.this));
        rvAlarmList.setItemAnimator(new DefaultItemAnimator());
        rvAlarmList.addItemDecoration(new DividerItemDecoration(EE_RepairActivity.this, 1));
        alarmInfoListAdapter = new AlarmInfoListAdapter(null);
        alarmInfoListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        alarmInfoListAdapter.isFirstOnly(true);
        rvAlarmList.setAdapter(alarmInfoListAdapter);

        rvChooseRepairList.setLayoutManager(new LinearLayoutManager(EE_RepairActivity.this));
        rvChooseRepairList.setItemAnimator(new DefaultItemAnimator());
        rvChooseRepairList.addItemDecoration(new DividerItemDecoration(EE_RepairActivity.this, 1));


        repairChooseTypeListAdapter = new RepairChooseTypeListAdapter(null);
        repairChooseTypeListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        repairChooseTypeListAdapter.isFirstOnly(true);
        rvChooseRepairList.setAdapter(repairChooseTypeListAdapter);
        repairChooseTypeListAdapter.setOnItemClickListener((adapter, view1, position) -> {
            if (repairBean == null) {
                showToast("页面信息未获取到，请重新获取", false);
                return;
            }
            Intent intent = new Intent();
            switch (position) {
                case 0:
                    repairBean.setMERepairType("addCap");
                    intent.setClass(EE_RepairActivity.this, EE_ChangeCleaverActivity.class);
                    break;
                case 1:
                    repairBean.setMERepairType("tool");
                    intent.setClass(EE_RepairActivity.this, EE_ChangeToolingActivity.class);
                    break;
                case 2:
                    repairBean.setMERepairType("screw");
                    intent.setClass(EE_RepairActivity.this, EE_ChangeScrewActivity.class);
                    break;
                case 3:
                    repairBean.setMERepairType("removeCap");
                    intent.setClass(EE_RepairActivity.this, EE_DownCleaverActivity.class);
                    break;
            }
            intent.putExtra("repairBean", repairBean);
            startActivityForResult(intent, 1101);
        });
    }

    private void requestInfoByEqpId(String eqpId) {
        JsonObject map = new JsonObject();
        map.addProperty("EqpID", eqpId);
        NetUtils.requestGetNet(this, "EMS_RepairMELoad", map, new FreeUI_DialogEntityCallBack<BaseResponseBean<RepairBean>>(
                new TypeToken<BaseResponseBean<RepairBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<RepairBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    repairBean = response.body().getResponse().getBody();
                    setPageData(repairBean);
                } else {
                    setPageData(new RepairBean());
                    repairBean = null;
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<RepairBean>> response) {
                super.onError(response);
                setPageData(new RepairBean());
                repairBean = null;
                uploadLog(response.getException());
                loadError(response.getException(), "EMS_RepairMELoad");
            }
        });
    }

    private void setPageData(RepairBean repairBean) {
        if (isFirst) {
            tvBdId.setText(repairBean.getBDId());
            tvBdVersion.setText(repairBean.getBDVer());
            etDesc.setText(repairBean.getFaultDesc());
            tbBuyoff.setChecked(repairBean.getIsBuyOff().equalsIgnoreCase("Y"));
            tbPeCheck.setChecked(repairBean.getISPECheck().equalsIgnoreCase("Y"));
            tvType.setText(repairBean.getRepairType());
            tvRepairRemark.setText(repairBean.getOpRemark());
            List<String> stringList = new ArrayList<>();
            for (RepairTypeBean typeBean : repairBean.getRepairTypeList()) {
                stringList.add(typeBean.getRepairType());
                if (repairBean.getRepairType().equals(typeBean.getRepairType())) {
                    setSubTypePop(typeBean.getRepairSubTypeList());
                }
            }
            typePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flType.getWidth(),
                    stringList, ivTypeArrow, (s, i) -> {
                        tvType.setText(s);
                        setSubTypePop(repairBean.getRepairTypeList().get(i).getRepairSubTypeList());
                    });

            alarmInfoListAdapter.setNewData(repairBean.getAlarmList());
            List<ChooseRepairBean> list = new ArrayList<>();
            list.add(new ChooseRepairBean("上劈刀", repairBean.getIsAddCapHis().equalsIgnoreCase("Y")));
            list.add(new ChooseRepairBean("Tooling更换", repairBean.getIsChangeToolHis().equalsIgnoreCase("Y")));
            list.add(new ChooseRepairBean("螺丝更换", repairBean.getIsChangeScrewHis().equalsIgnoreCase("Y")));
            list.add(new ChooseRepairBean("下劈刀", repairBean.getIsRemoveCapHis().equalsIgnoreCase("Y")));
            repairChooseTypeListAdapter.setNewData(list);
        }
        isFirst = false;
    }

    private void setSubTypePop(List<String> subTypeList) {
        if (subTypeList.size() > 0) {
            llSubType.setVisibility(View.VISIBLE);
            childPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flRepairChild.getWidth(),
                    subTypeList, ivRepairChildArrow, (s2, i2) -> {
                        tvRepairChild.setText(s2);
                        if (s2.equals("新建recipe")) {
                            isNewRcp = true;
                            tbPeCheck.setChecked(false);
                            tbPeCheck.setEnabled(false);
                            tbBuyoff.setChecked(true);
                            tbBuyoff.setEnabled(false);
                        } else {
                            isNewRcp = false;
                            tbPeCheck.setChecked(false);
                            tbPeCheck.setEnabled(true);
                            tbBuyoff.setChecked(false);
                            tbBuyoff.setEnabled(true);
                        }
                    });
        } else {
            llSubType.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        tbBuyoff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                llDcType.setVisibility(b ? View.VISIBLE : View.GONE);
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("维修");
        freeUI_titleView.setLeftListener(view -> showBackDialog(EE_RepairActivity.this));
        freeUI_titleView.setRightListener("提交", v -> {
            if (MyUtils.isFastClick()){
                showToast("您点击的太快了",false);
                return;
            }
            if (repairBean == null) {
                showToast("未获取到页面信息，请重新扫描设备编号", false);
                etEqpId.setText("");
                MyUtils.setEditTextFocus(etEqpId);
                return;
            }
            String desc = etDesc.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(desc)) {
                showToast("请输入故障描述", false);
                return;
            }
            String type = tvType.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(type)) {
                showToast("请选择报修类型", false);
                return;
            }
            String child = tvRepairChild.getText().toString().trim();
            if (llSubType.getVisibility() == View.VISIBLE && FreeApi_StringUtils.isEmpty(child)) {
                showToast("请选择维修子类", false);
                return;
            }
            String dcType = tvDcType.getText().toString().trim();
            if (llDcType.getVisibility() == View.VISIBLE && FreeApi_StringUtils.isEmpty(dcType)) {
                showToast("请选择DcType", false);
                return;
            }
            boolean isChange = false;
            for (ChooseRepairBean chooseRepairBean : repairChooseTypeListAdapter.getData()) {
                if (chooseRepairBean.isOk()) {
                    isChange = true;
                    break;
                }
            }
            String remark = etRemark.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(remark) && !isChange) {
                showToast("未做任何维修，请填写备注", false);
                return;
            }

            if (repairBean.getIsAddCapHis().equalsIgnoreCase("Y") ||
                    repairBean.getIsChangeToolHis().equalsIgnoreCase("Y") ||
                    repairBean.getIsChangeScrewHis().equalsIgnoreCase("Y") ||
                    type.equals("改产品或封装") || type.equals("换劈刀")) {
                if (!tbBuyoff.isChecked()) {
                    tbBuyoff.setChecked(true);
                    showToast("Buyoff未勾选，已经帮您勾选，请重新提交", false);
                    return;
                }
            }
            repairBean.setFaultDesc(desc);
            repairBean.setRepairType(type);
            repairBean.setRepairSubType(child);
            repairBean.setIsBuyOff(tbBuyoff.isChecked() ? "Y" : "N");
            repairBean.setIsNewRcp(isNewRcp ? "Y" : "N");
            repairBean.setISPECheck(tbPeCheck.isChecked() ? "Y" : "N");
            repairBean.setOpRemark(tvRepairRemark.getText().toString());
            repairBean.setRemark(remark);
            repairBean.setDcType(dcType);

            Intent intent = new Intent();
            intent.setClass(EE_RepairActivity.this, CheckListActivity.class);
            intent.putExtra("repairBean", repairBean);
            startActivity(intent);
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1101) {
            if (resultCode == 2101) {
                repairChooseTypeListAdapter.getData().get(0).setOk(true);
            } else if (resultCode == 2102) {
                repairChooseTypeListAdapter.getData().get(1).setOk(true);
            } else if (resultCode == 2103) {
                repairChooseTypeListAdapter.getData().get(2).setOk(true);
            } else if (resultCode == 2104) {
                repairChooseTypeListAdapter.getData().get(3).setOk(true);
            }
            repairChooseTypeListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        String eqpId = etEqpId.getText().toString().trim();
        if (eqpId.length() > 0) {
            requestInfoByEqpId(eqpId);
        }
    }

    @OnClick({R.id.flType, R.id.flRepairChild, R.id.flDcType})
    public void onViewClicked(View view) {
        if (MyUtils.isFastClick()){
            showToast("您点击的太快了",false);
            return;
        }
        switch (view.getId()) {
            case R.id.flDcType:
                if (repairBean != null) {
                    dcTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flDcType.getWidth(),
                            repairBean.getDcTypeList(), ivDcTypeArrow, (s, i) -> {
                                tvDcType.setText(s);
                            });
                    if (dcTypePop.isShowing()) {
                        dcTypePop.dismiss();
                    } else {
                        FreeApi_PopUtils.setArrowShow(ivDcTypeArrow);
                        dcTypePop.showAsDropDown(flDcType, 0, 0);
                    }
                }
                break;
            case R.id.flType:
                if (typePop != null) {
                    if (typePop.isShowing()) {
                        typePop.dismiss();
                    } else {
                        FreeApi_PopUtils.setArrowShow(ivTypeArrow);
                        typePop.showAsDropDown(flType, 0, 0);
                    }
                }
                break;
            case R.id.flRepairChild:
                if (childPop != null) {
                    if (childPop.isShowing()) {
                        childPop.dismiss();
                    } else {
                        FreeApi_PopUtils.setArrowShow(ivRepairChildArrow);
                        childPop.showAsDropDown(flRepairChild, 0, 0);
                    }
                }
                break;
        }
    }
}
